package com.alex.chat.web;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class VelocityFilter implements Filter {

	private RequestDispatcher velocityRequestDispatcher;
	
	@Override
	public void init(FilterConfig config) throws ServletException {
		velocityRequestDispatcher = config.getServletContext().getNamedDispatcher("velocity-servlet");
	}
	
	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		if (request instanceof HttpServletRequest) {
			HttpServletRequest httpRequest = (HttpServletRequest) request;
			if (httpRequest.getRequestURI().endsWith(".vm")) {
				request.setCharacterEncoding("UTF-8");
				response.setContentType("text/html; charset=UTF-8");
				velocityRequestDispatcher.forward(request, response);
				return;
			}
		}
		chain.doFilter(request, response);
	}
}
